#include"login.h"
/* Usage:  */
int regi(int netfd,MYSQL*mysql,char*username,int*user_base_addr ,char*errbuf){
    TLV_t TLV;
    TLV.msg=(char*)calloc(1024,sizeof(char));
    char *p=(char*)calloc(1024,sizeof(char));
    sprintf(p,"select id from userdata where name = %s ;",username);
    mysql_query(mysql,p);
    MYSQL_RES*rows=mysql_store_result(mysql);
    if(rows!=NULL){
        int a=0;
        send(netfd,&a,sizeof(int),0);
        sprintf(errbuf,"You have been registed\n");
        return -1;
    }
    bzero(p,strlen(p));
char salt[21]={0};
salt[0]='$';
salt[1]='6';
salt[2]='$';
salt[19]='$';
salt[20]=0;
char val[]="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./";
srand(time(NULL));
for(int i=3;i<19;i++){
    salt[i]=val[rand()%64];
}
printf("salt=%s\n",salt);
char *password;
recv(netfd,&TLV.type,sizeof(int),MSG_WAITALL);
recv(netfd,&TLV.len,sizeof(int),MSG_WAITALL);
recv(netfd,&TLV.msg,TLV.len,MSG_WAITALL);
password=crypt(TLV.msg,salt);
printf("password=%s\n",password);
bzero(p,strlen(p));
    sprintf(p,"insert into userdata (user,salt,password,is_deleted) value(%s varchar(30),%s varchar(30),%s varchar(50),0 int);",username,salt,password);
    mysql_query(mysql,p);
    bzero(p,strlen(p));
    sprintf(p,"insert into vft (filename,user,parent_id,type,path)value(%s varchar(50),%s varchar(30),-1 int,d,/%s varchar(100));",username,username,username);
    mysql_query(mysql,p);
bzero(p,strlen(p));
    sprintf(p,"select id from vft where path = /%s;",username);
    rows=mysql_store_result(mysql);
    MYSQL_ROW row=mysql_fetch_row(rows);
    *user_base_addr=atoi(row[0]);
    return 0;
}
int login(int netfd,MYSQL *mysql,char*username,int *user_base_addr,char*errbuf){
    TLV_t TLV;
    TLV.msg=(char*)calloc(1024,sizeof(char));
    char *p=(char*)calloc(1024,sizeof(char));
    sprintf(p,"select id,salt,password from userdata where path = /%s ;",username);
    mysql_query(mysql,p);
    MYSQL_RES*rows=mysql_store_result(mysql);
    if(rows==NULL){
        int a=0;
        send(netfd,&a,sizeof(int),0);
        sprintf(errbuf,"Can not find user\n");
            return -1;
    }
        MYSQL_ROW row=mysql_fetch_row(rows);
    int access=0;
    while(access==1){
        send(netfd,&access,sizeof(int),MSG_NOSIGNAL);
        int res=recv(netfd,&TLV.type,sizeof(int),MSG_WAITALL);
        if(res==0){
            sprintf(errbuf,"Clint closed\n");
            return -1;
        }
        recv(netfd,&TLV.len,sizeof(int),MSG_WAITALL);
        recv(netfd,&TLV.msg,TLV.len,MSG_WAITALL);
        char *password;
        password=crypt(TLV.msg,row[1]);
        if(strcmp((char*)password,row[2])==0){
            access=1;
        }
    }
*user_base_addr=atoi(row[0]);
    return 0;

}

